<template>
  <!--页面搭建-杜思成-->
  <layout-card
    v-model="search"
    :filters="ismapOptions"
    headline="信息列表"
    headtitle="数据筛选"
    :hasButton="true"
    @search-change="getData"
    @search-reset="searchReset"
  >
    <template #action>
      <el-button type="primary" @click="handleCreate('threshold')"
        >维护提示</el-button
      >
      <el-button
        type="primary"
        @click="handleCreate('export')"
        :disabled="tabledata.length === 0"
        >导出</el-button
      >
      <el-button type="primary" @click="handleCreate('download')"
        >模版下载</el-button
      >
      <el-upload
        style="display: inline-block; margin-left: 12px; margin-right: 12px"
        ref="upload"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleImport"
      >
        <el-button type="primary">导入</el-button>
      </el-upload>
      <!-- <el-button type="primary" @click="handleCreate('import')">导入</el-button> -->
      <el-button type="primary" @click="handleCreate('add')"
        >房屋登记</el-button
      >
    </template>
    <table-common
      stripe="true"
      :columns="mapListColumns"
      :loading="loading"
      :pagination="pager"
      :table-data="tabledata"
      size="large"
      @current-change="changeCurrent"
      @size-change="changePageSize"
      @sort-change="sortChange"
    >
      <!-- 维护图标提示 -->
      <template #houseName="{ row }">
        <el-text type="primary" v-if="remindList.includes(row.houseId)">
          <img
            src=""
            class="img"
            width="18"
            height="18"
            data-v-fae5bece=""
            style="background-color: red"
          />
        </el-text>
        {{ row["houseName"] }}
      </template>
      <template #action="{ row }">
        <!-- 自定义操作栏示例  -->
        <el-button class="link-btn" @click="handleEdit(row)" link type="primary"
          >编辑</el-button
        >
        <el-popconfirm
          title="是否删除?"
          confirmButtonText="确定"
          cancelButtonText="取消"
          @confirm="() => DeletRow(row)"
        >
          <template #reference>
            <el-button class="link-btn" link type="danger">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </table-common>
  </layout-card>
  <!-- 维护提示 -->
  <edit-dialog
    class="maintenance"
    :centerDialogVisible="thresholdDialogVisible"
    :tilte="addTilte"
    :key="timer"
    :defaultButton="false"
    :width="500"
    @cancel="handleCancel"
    :close-on-click-modal="false"
  >
    <template #content>
      <filter-bar
        :filters="ismapListFilters"
        :close-collapse="true"
        ref="remindRef"
      ></filter-bar>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </span>
    </template>
  </edit-dialog>
  <!-- 地图弹出框 -->
  <edit-dialog
    :centerDialogVisible="addDialogVisible"
    :tilte="addTilte"
    :key="timer"
    :defaultButton="false"
    :width="950"
    @cancel="handleCancel"
    :close-on-click-modal="false"
  >
    <template #content>
      <div style="width: 100%; height: 500px; border: 1px solid #000">
        <map-control
          @mapClick.once="mapClick"
          @mapLoad="mapLoadEvent"
        ></map-control>
      </div>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="handleCancel">取消</el-button>
        <el-button class="buttonOk" type="primary" @click="handleNext"
          >下一步</el-button
        >
        <el-button class="buttonOk" @click="handleSkip" plain>跳过</el-button>
      </span>
    </template>
  </edit-dialog>
  <!-- 编辑弹出框 -->
  <edit-dialog
    class="edit"
    :centerDialogVisible="saveDialogVisible"
    :tilte="addTilte"
    :key="timer"
    :defaultButton="false"
    :width="950"
    @cancel="handleCancel"
    :close-on-click-modal="false"
  >
    <template #content>
      <filter-bar
        :filters="isdialogOptions"
        :hasButton="false"
        :rules="rules"
        ref="FilterRef"
        :close-collapse="true"
      ></filter-bar>
    </template>

    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="handleCancel">取消</el-button>
        <el-button class="buttonOk" @click="handleBack">返回</el-button>
        <el-button class="buttonOk" type="primary" @click="handleSave"
          >保存</el-button
        >
      </span>
    </template>
  </edit-dialog>
</template>

<script lang="ts" setup>
import { computed, ref, reactive, onBeforeMount, nextTick } from "vue";
import LayoutCard from "@/components/LayoutCard/index.vue";
import TableCommon from "@/components/TableCommon/index.vue";
import editDialog from "@/components/editDialog/index.vue";
import {
  housePageList,
  houseDeleteRow,
  houseModuleDown,
  houseImport,
  exportPageList,
  append,
  change,
  getUserInfo,
} from "@/api/eqpt/houseManger";
import { mapListColumns } from "@/views/eqpt/houseManger/config/columns";
import {
  mapOptions,
  dialogOptions,
  mapListFilters,
} from "@/views/eqpt/houseManger/config/filters";
import {
  FormRules,
  ElMessage,
  UploadInstance,
  ElMessageBox,
  ElText,
} from "element-plus";

import FilterBar from "@/components/FilterBar/index.vue";
import { getResource, postResource } from "@/api/resource";

import { useStore } from "vuex";
// 地图控件
import mapControl from "@/components/map/index.vue";
import { store } from "@/components/map/mapStore";

const stores = useStore();
const organTree = stores.state.user.organTree; // 获取树
const isdialogOptions = ref(dialogOptions);
const ismapOptions = ref(mapOptions);
const ismapListFilters = ref(mapListFilters);
const thresholdDialogVisible = ref(false);
const addDialogVisible = ref(false);
const saveDialogVisible = ref(false);
const timer = ref();
const addTilte = ref(""); // 弹出框名称
const houseId = ref("");
// 最近一次维保-年
const year = ref(null);
// 最近一次维保-月
const month = ref(null);
// 最近一次维保-日
const day = ref(null);
// 存放需要维护提醒的 id
const remindList = ref([]);
// 分页和数据展示参数
const current = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tabledata = ref([]);
const search = ref({
  houseType:null,
  region:null,
  state:null
});
const pager = computed(() => ({
  currentPage: current.value,
  pageSize: pageSize.value,
  total: total.value,
  pageCount:
    Math.ceil(total.value / pageSize.value) === 0
      ? 1
      : Math.ceil(total.value / pageSize.value),
}));

// 校验规格参数
const validateRule = ref();
/**
 * @functionName 分页、查询、排序、删除功能
 * @author 杜思成
 * @date 2023-08-08 17:46:09
 * @version V1.0.0
 */
const changeCurrent = (value: number) => {
  current.value = value;
  getData();
};
const changePageSize = (size: number) => {
  pageSize.value = size;
  getData();
};
const order = ref([
  {
    column: "state",
    method: "asc",
  },
  {
    column: "lastUpdateTime",
    method: "desc",
  },
]);
/**
 * @functionName 获取数据
 * @author 彭庆楠
 * @date 2023-08-08 17:47:31
 * @version V1.0.0
 * @return
 */
const getData = async () => {
  const searchList = {
    houseCode: search.value?.houseCode,
    state: search.value?.state,
    region: search.value?.region,
    houseType: search.value?.houseType,
    houseName: search.value?.houseName,
    order: order.value,
  };
  const playout = {
    pageNum: current.value,
    pageSize: pageSize.value,
    condition: searchList,
  };
  await housePageList(playout).then((res) => {
    tabledata.value = res?.data?.list;
    total.value = res?.data?.total;
    if (res?.code) {
      // 获取数据成功，处理数据格式
      res?.data?.list.forEach((item) => {
        // 类型
        ismapOptions.value[1].inputProps.options.forEach((item1) => {
          if (item.houseType === item1.value) {
            item.houseType = item1.label;
          }
        });
        // 区域
        ismapOptions.value[3].inputProps.options.forEach((item2) => {
          if (item.region === item2.value) {
            item.region = item2.label;
          }
        });
        // 性质
        isdialogOptions.value[11].inputProps.options.forEach((item3) => {
          if (item.nature === item3.value) {
            item.nature = item3.label;
          }
        });
        // 功能
        isdialogOptions.value[12].inputProps.options.forEach((item4) => {
          if (item.ability === item4.value) {
            item.ability = item4.label;
          }
        });
      });
    } else {
      ElMessage.error("获取失败");
    }
  });
  nextTick(() => {
    handleSubmit(remindtype);
  });
};
/**
 * @functionName 排序事件
 * @param {any} data 传入的某一列的列名和升降序
 * @author 彭庆楠
 * @date 2023-08-17 17:48:41
 * @version V1.0.0
 * @return
 */
const sortChange = (data: any) => {
  const method = data.order === "ascending" ? "asc" : "desc";
  order.value[0].column = data.prop;
  order.value[0].method = method;
  getData();
};
// 删除
const DeletRow = (row: any) => {
  const formData = new FormData();
  formData.append("houseId", row.houseId);
  const code = houseDeleteRow(formData);
  code.then((res) => {
    if (res?.code) {
      getData();
      ElMessage({
        message: "删除成功",
        type: "success",
      });
    } else {
      ElMessage.error("删除失败");
    }
  });
};
const CacheState = JSON.parse(
  window.localStorage.getItem("CacheState") as string
);
const name = ref("");
const userId = ref("");
const organId = ref("");
const organName = ref("");
name.value = CacheState.user.userInfo.name;
userId.value = CacheState.user.userInfo.userId;
organId.value = CacheState.user.userInfo.organId;
organName.value = CacheState.user.userInfo.organName;
const upload = ref<UploadInstance>();
// 导入
const btnLoading = ref(false); // 导入按钮加载状态
/**
 * @functionName 导入功能
 * @param {any} file
 * @description
 * @author 蒋浩东
 * @date 2023-08-08 17:49:49
 * @version V1.0.0
 * @return
 */
const handleImport = (file: any) => {
  const index = file.name.lastIndexOf("."); // 根据文件名找到最后一个‘.’的索引
  const suffixName = file.name.substr(index); // 根据索引截取，得到后缀名
  if (suffixName !== ".xlsx" && suffixName !== ".xls") {
    ElMessage({
      message: "此文件不是excel文件",
      type: "warning",
    });
    upload.value?.clearFiles();
  } else {
    const formData = new FormData();
    formData.append("multipartFile", file.raw);
    formData.append("id", userId.value);
    formData.append("name", name.value);
    formData.append("organId", organId.value);
    formData.append("organName", organName.value);

    houseImport(formData)
      .then((res: any) => {
        if (res.code === "200") {
          ElMessage.success("导入成功");
          pager.value.currentPage = 1;
          pager.value.pageSize = 10;
          getData();
          setTimeout(() => {
            upload.value?.clearFiles();
          }, 1000);
        } else {
          ElMessage.error(res?.message || "导入失败");
          setTimeout(() => {
            upload.value?.clearFiles();
          }, 1000);
        }
        btnLoading.value = false;
      })
      .catch((err: any) => {
        ElMessage.error(err?.message || "导入失败");
        setTimeout(() => {
          upload.value?.clearFiles();
        }, 1000);
      });
  }
};

const maplist = new Map();
// 树形所属单位
const organlist = async () => {
  isdialogOptions.value[9].inputProps.data = [];
  isdialogOptions.value[15].inputProps.data = [];
  organTree.forEach((e: any) => {
    const type = {
      value: e.data.organId,
      label: e.data.name,
      children: [],
    };
    if (e.children) {
      e.children.forEach((c: any) => {
        const ctype = {
          value: c.data.organId,
          label: c.data.name,
          children: [],
        };
        if (c.children) {
          c.children.forEach((cc: any) => {
            const cctype = {
              value: cc.data.organId,
              label: cc.data.name,
            };
            ctype.children.push(cctype);
            maplist.set(cc.data.organId, cc.data.name);
          });
        }
        type.children.push(ctype);
        maplist.set(c.data.organId, c.data.name);
      });
    }
    isdialogOptions.value[9].inputProps.data.push(type);
    isdialogOptions.value[15].inputProps.data.push(type);
  });
};
// 编辑栏处于 编辑 还是 增加 状态判断
let dialogState = "";
/**
 * @functionName 新增、编辑弹出框
 * @param {any} val 判断打开那个弹窗
 * @description
 * @author 彭庆楠
 * @date 2023-08-08 17:53:22
 * @version V1.0.0
 * @return
 */
const handleCreate = (val: any) => {
  timer.value = new Date().getTime();
  if (val === "threshold") {
    // 弹窗标题
    thresholdDialogVisible.value = true;
    addTilte.value = "设置维护提醒";
    ismapListFilters.value[0].defaultValue = remindtype.beforePeriod;
    ismapListFilters.value[1].defaultValue = remindtype.prompt;
  } else if (val === "export") {
    const date = new Date();
    const dateNumber =
      date.getFullYear() * 1e4 + (date.getMonth() + 1) * 1e2 + date.getDate();
    // 导出
    exportPageList(search?.value).then((res) => {
      const a = document.createElement("a");
      a.href = URL.createObjectURL(new Blob([res]));
      a.download = "房屋动态管理" + dateNumber + ".xlsx";
      a.click();
    });
  } else if (val === "download") {
    houseModuleDown().then((res) => {
      const a = document.createElement("a");
      a.href = URL.createObjectURL(new Blob([res]));
      a.download = "房屋动态管理导入模板.xlsx";
      a.click();
    });
  } else {
    // 弹窗标题
    dialogState = "add";
    addTilte.value = "新增房屋登记";
    addDialogVisible.value = true;
    isdialogOptions.value.forEach((e) => {
      e.defaultValue = undefined;
    });
    isdialogOptions.value[8].events.click = function () {
      let val = isdialogOptions.value[8].defaultValue;
      val = val === undefined ? "未选择" : val;
      ElMessageBox.confirm("", "是否修改地图坐标", {
        confirmButtonText: "修改坐标",
        cancelButtonText: "取消修改",
        type: "warning",
      }).then(() => {
        mapLoadEvent();
        handleBack();
      });
    };
  }
};
const handleEdit = async (row: any) => {
  houseId.value = row.houseId;
  dialogState = "edit";
  saveDialogVisible.value = true;
  const linkUserList = ref([]) as any; //联系人回显
  // 该循环用于进行编辑页面数据回显，需要字段对应
  isdialogOptions.value.forEach(async (e) => {
    if (row[e.prop] !== null) {
      e.defaultValue = row[e.prop];
    }
    if (e.prop === "maintainTime") {
      e.defaultValue = row[e.prop];
    }
    if (e.prop === "linkUser") {
      e.defaultValue = row.linkUserName;
    }
    if (e.prop === "coordinate") {
      const val = ref([]) as any;
      if (row[e.prop] === "无") {
        e.defaultValue = "";
      } else {
        vcoordinate.value = row[e.prop];
        if (row[e.prop]?.length && row[e.prop] instanceof Array) {
          if (!(row[e.prop][0] instanceof Array)) {
            row[e.prop].forEach((e: any) => {
              const v = [];
              v.push(e.latitude);
              v.push(e.longitude);
              val.value.push(v);
            });
            e.defaultValue = val.value;
          }
        } else {
          e.defaultValue = row[e.prop];
        }
      }
      e.events.click = function () {
        let val = e.defaultValue;
        val = val === undefined ? "未选择" : val;
        ElMessageBox.confirm("", "是否修改地图坐标", {
          confirmButtonText: "修改坐标",
          cancelButtonText: "取消修改",
          type: "warning",
        }).then(() => {
          handleBack();
          // mapLoadEvent();
        });
      };
    }
    if (e.prop === "useOrgan") {
      maplist.forEach((key, value) => {
        if (key === row.organNames) {
          e.defaultValue = value;
        }
      });
      const params = ref({
        groupIds: [] as any,
      });
      params.value.groupIds.length = 0;
      params.value.groupIds.push(e.defaultValue);
      await getUserInfo(params.value).then((resp) => {
        resp.data.forEach((d: any) => {
          const option = ref({
            label: d.userName,
            value: d.userId,
          });
          linkUserList.value.push(option.value);
        });
      });
      isdialogOptions.value[16].inputProps.options = linkUserList.value;
    }
    if (e.prop === "dutyOrganName") {
      maplist.forEach((key, value) => {
        if (key === row.dutyOrganName) {
          e.defaultValue = value;
        }
      });
    }
  });
  timer.value = new Date().getTime();
  addTilte.value = "编辑房屋登记";
};
/**
 * @functionName 取消功能
 * @author 杜思成
 * @date 2023-08-08 17:55:02
 * @version V1.0.0
 */
const handleCancel = () => {
  thresholdDialogVisible.value = false;
  addDialogVisible.value = false;
  saveDialogVisible.value = false;
  isdialogOptions.value.forEach((e) => {
    e.defaultValue = "";
    if (e.prop === "linkUser") {
      e.inputProps.options = [];
    }
  });
  if(vcoordinate.value){
    vcoordinate.value.length = 0;
  }
  if(myRings.value){
    myRings.value.length = 0;
  }
  getData();
};
const vcoordinate = ref([]) as any;
//addNewData 新增是表单里的数据
const addNewData = ref({});
//跳过
const handleSkip = () => {
  addDialogVisible.value = false;
  saveDialogVisible.value = true;
  if(myRings.value){
    myRings.value.length = 0;
  }
  showOldData();
};
// 点击下一步
const handleNext = () => {

  if(!myRings.value){
    ElMessage({
      message: "请选择地图坐标",
      type: "error",
    });
    return
  }
  addDialogVisible.value = false;
  saveDialogVisible.value = true;
  // vcoordinate.value.length = 0;
  isdialogOptions.value[8].defaultValue = "";
  let arr = ref([]) as any;
  myRings.value.forEach((e) => {
    e.forEach((r: any) => {
      const arrs = ref({
        latitude: "",
        longitude: "",
      });
      arrs.value.latitude = r[0];
      arrs.value.longitude = r[1];
      arr.value.push(arrs.value);
    });
    vcoordinate.value = arr.value;
  });
  setTimeout(function() {
    if (FilterRef.value) {
      FilterRef.value.setFieldsValue({
        coordinate: myRings.value,
      });
      isdialogOptions.value[8].defaultValue =
        FilterRef.value.getParams().coordinate;
    } else {
      isdialogOptions.value[8].defaultValue = myRings.value;
    }
    showOldData();
  }, 100)
};
// 新增表单回显赋值
const showOldData = () => {
  isdialogOptions.value.forEach(async (e) => {
    console.log(e)
    e.defaultValue = addNewData.value[e.prop];
  });
};
// 点击返回
const handleBack = () => {
  saveDialogVisible.value = false;
  addDialogVisible.value = true;
  addNewData.value = FilterRef.value.getParams();
};
const FilterRef = ref({});
const linkUserName = ref("");
const linkUserId = ref("");
const handleUserInfo = async (value: any, link: any) => {
  const params = ref({
    groupIds: [] as any,
  });
  params.value.groupIds.length = 0;
  params.value.groupIds.push(value);
  // const a = ref("");
  await getUserInfo(params.value).then((resp) => {
    resp.data.forEach((d: any) => {
      if (d.userId === link) {
        linkUserName.value = d.userName;
        linkUserId.value = d.userId;
      } else if (d.userName === link) {
        linkUserName.value = d.userName;
        linkUserId.value = d.userId;
      }
    });
  });
  // linkUserName.value = a.value;
};

/**
 * @functionName 保存发送请求功能
 * @author 杜思成
 * @date 2023-08-08 17:55:36
 * @version V1.0.0
 */
const handleSave = async () => {
  const { linkPhone, houseName, price, rent, area, houseCode, condition } =
    FilterRef.value.getParams();
  const newlinkPhone = linkPhone ? linkPhone.replace(/\s+/g, "") : linkPhone;
  const newhouseName = houseName ? houseName.replace(/\s+/g, "") : houseName;
  const newprice = price ? price.replace(/\s+/g, "") : price;
  const newrent = rent ? rent.replace(/\s+/g, "") : rent;
  const newarea = area ? area.replace(/\s+/g, "") : area;
  const newhouseCode = houseCode ? houseCode.replace(/\s+/g, "") : houseCode;
  const newcondition = condition ? condition.replace(/\s+/g, "") : condition;
  await nextTick(() => {
    FilterRef.value.setFieldsValue({
      linkPhone: newlinkPhone,
      houseName: newhouseName,
      price: newprice,
      rent: newrent,
      area: newarea,
      houseCode: newhouseCode,
      condition: newcondition,
    });
  });
  const validateRulefit = await FilterRef.value.validateRuleFormRef();
  const data = FilterRef.value.getParams();
  if (vcoordinate.value.length === 0) {
    data.coordinate.forEach((e: any, index: any) => {
      data.coordinate[index] = {
        latitude: e[0],
        longitude: e[1],
      };
    });
  } else {
    data.coordinate = vcoordinate.value;
  }
  await handleUserInfo(data.useOrgan, data.linkUser);
  data.houseId = houseId.value;
  const addData = ref<any>({
    ...data,
    maintainTime:
      data.maintainTime === undefined
        ? undefined
        : getDataTime(data.maintainTime),
    useOrgan:
      data.useOrgan === undefined
        ? undefined
        : [
            {
              organId: data.useOrgan,
              organName: maplist.get(data.useOrgan),
            },
          ],
    dutyOrgan:
      data.dutyOrganName === undefined
        ? undefined
        : {
            organId: data.dutyOrganName,
            organName: maplist.get(data.dutyOrganName),
          },
    linkUser:
      data.linkUser === undefined
        ? undefined
        : {
            id: linkUserId.value,
            name: linkUserName.value,
          },
  });
  if (!validateRulefit) {
    console.log(validateRulefit);
  } else {
    // 添加请求
    if (dialogState === "add") {
      for (let el of data) {
        if (typeof el === "string") {
          el = el.trim();
        }
      }
      await append(addData.value)
        .then(() => {
          ElMessage({
            message: "添加成功",
            type: "success",
          });
          handleCancel();
          getData();
        })
        .catch((err) => {
          ElMessage({
            message: "添加失败," + err.message,
            type: "error",
          });
        });
    } else {
      // 处理类型请求是的值
      ismapOptions.value[1].inputProps.options.forEach((item: any) => {
        if (item.label === addData.value.houseType) {
          addData.value.houseType = item.value;
        }
      });
      // 处理区域请求是的值
      ismapOptions.value[3].inputProps.options.forEach((item: any) => {
        if (item.label === addData.value.region) {
          addData.value.region = item.value;
        }
      });
      // 编辑功能
      await change(addData.value)
        .then(() => {

          ElMessage({
            message: "编辑成功",
            type: "success",
          });
          handleCancel();
          getData();
        })
        .catch((err: any) => {
          console.log(err);
          ElMessage({
            message: "编辑失败，"+err.message,
            type: "error",
          });
        });
    }
  }
};
//时间处理
const getDataTime = (dataTime: string) => {
  const date = new Date(dataTime);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  const seconds = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

/**
 * @functionName 电话校验
 * @author 蒋好东
 * @date 2023-08-23 11:20:22
 * @version V1.0.0
 */
const validatorPhone = (rule: any, value: any, callback: any) => {
  const ab = /^[1][3,4,5,7,8][0-9]{9}$/;
  if (value) {
    if (value.includes(" ")) {
      value = value.replace(/\s+/g, "");
    }
  }
  if (rule) {
    if (value === "") {
      callback();
    } else {
      if (ab.test(value) === false && value !== undefined) {
        callback(new Error("请输入正确电话号码"));
      } else {
        callback();
      }
    }
  }
};

/**
 * @functionName 面积、单价、月积金校验功能
 * @author 蒋好东
 * @date 2023-08-23 11:21:36
 * @version V1.0.0
 */
const validatorArea = (rule: any, value: any, callback: any) => {
  const apr = /(^(\+|\+)?\d+(\.\d+)$)|(^[0-9]{1,7}$)/;
  if (value) {
    if (value.includes(" ")) {
      value = value.replace(/\s+/g, "");
    }
  }
  if (rule) {
    if (value === "") {
      callback();
    } else {
      if (apr.test(value) === false && value !== undefined) {
        if (value > 9999999) {
          callback(new Error("面积不能超过9999999"));
        } else {
          callback(new Error("请输入正确的面积"));
        }
      } else {
        callback();
      }
    }
  }
};
const validatorPrice = (rule: any, value: any, callback: any) => {
  const apr = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/;
  if (value) {
    if (value.includes(" ")) {
      value = value.replace(/\s+/g, "");
    }
  }
  console.log(value)
  if (!apr.test(value) && value !== undefined  && value !== '') {
    callback(new Error("请输入正确的单价"));
  } else {
    callback();
  }
};
const validatorRent = (rule: any, value: any, callback: any) => {
  const apr = /(^(\+|\+)?\d+(\.\d+)$)|(^[0-9]{1,7}$)/;
  if (value) {
    if (value.includes(" ")) {
      value = value.replace(/\s+/g, "");
    }
  }
  if (rule) {
    if (value === "") {
      callback();
    } else {
      if (apr.test(value) === false && value !== undefined) {
        if (value > 9999999) {
          callback(new Error("月租金不能超过9999999"));
        } else {
          callback(new Error("请输入正确的月租金"));
        }
      } else {
        callback();
      }
    }
  }
};
const validatorHouseCode = (rule: any, value: any, callback: any) => {
  const apr = /^[a-zA-Z]([-_a-zA-Z0-9])+$/;
  if (value) {
    if (value.includes(" ")) {
      value = value.replace(/\s+/g, "");
    }
  }
  if (rule) {
    if (value === "") {
      callback();
    } else {
      if (apr.test(value) === false && value !== undefined) {
        callback();
      } else {
        callback();
      }
    }
  }
};
const validatorCondition = (rule: any, value: any, callback: any) => {
  const apr = /^[a-zA-Z]([-_a-zA-Z0-9])+$/;
  if (value) {
    if (value.includes(" ")) {
      value = value.replace(/\s+/g, "");
    }
  }
  if (rule) {
    if (value === "") {
      callback();
    } else {
      if (apr.test(value) === false && value !== undefined) {
        callback();
      } else {
        callback();
      }
    }
  }
};

// 校验
const rules = reactive<FormRules>({
  houseName: [
    { required: true, message: "请输入名称", trigger: "blur" },
    { required: true, message: "请输入名称", trigger: "change" },
  ],
  coordinate: [
    { required: true, message: "请输入坐标", trigger: "blur" },
    { required: true, message: "请输入坐标", trigger: "change" },
  ],
  linkPhone: [{ validator: validatorPhone, trigger: "blur" }],
  area: [{ validator: validatorArea, trigger: "blur", type: "number" }],
  price: [{ validator: validatorPrice, trigger: "blur" }],
  rent: [{ validator: validatorRent, trigger: "blur" }],
  houseCode: [{ validator: validatorHouseCode, trigger: "blur" }],
  condition: [{ validator: validatorCondition, trigger: "blur" }],
});

/**
 * @functionName 重置功能
 * @param {FilterDataType} data
 * @description
 * @author 杜思成
 * @date 2023-08-17 17:55:57
 * @version V1.0.0
 * @return
 */
const searchReset = (data: FilterDataType) => {
  search.value = data;
  pager.value.currentPage = 1;
  pager.value.pageSize = 10;
  getData();
};
/**
 * @functionName 获取字典
 * @param {any} data
 * @author 杜思成
 * @date 2023-08-08 17:56:22
 * @version V1.0.0
 */
const getHouseCategory = async (data: any) => {
  const res = await getResource(data);
  if (data === "house_category") {
    ismapOptions.value[1].inputProps.options = [{
        label: '全部',
        value: null
    }]
    ismapOptions.value[1].inputProps.options =
      ismapOptions.value[1].inputProps.options.concat(res.data.properties.meta);
    isdialogOptions.value[1].inputProps.options = res.data.properties.meta;
  } else if (data === "house_region") {
    ismapOptions.value[3].inputProps.options = [{
        label: '全部',
        value: null
    }]
    ismapOptions.value[3].inputProps.options =
      ismapOptions.value[3].inputProps.options.concat(res.data.properties.meta);
    isdialogOptions.value[7].inputProps.options = res.data.properties.meta;
  } else if (data === "house_ability") {
    isdialogOptions.value[12].inputProps.options = res.data.properties.meta;
  } else if (data === "house_nature") {
    isdialogOptions.value[11].inputProps.options = res.data.properties.meta;
  }
};
let drawLayer;
/**
 * 绘制图形
 * @param val 地图坐标
 * @param data 房屋数据
 */
const drawAreaOnMap = (data) => {
  if (!Array.isArray(data)) {
    return;
  }
  const coordinate = [];
  data.forEach((item) => {
    coordinate.push([item.latitude, item.longitude]);
  });
  data = coordinate;
  let sectorsym;
  sectorsym = store.BNSymbol.polygonSymbol(
    "solid",
    store.BNSymbol.simpleLineSymbol("solid", "#2F7DF1", 1),
    "#bad4fb"
  );
  // 要素图层
  const polygon = store.BNGeometry.createPolygon({
    rings: data,
    spatialReference: store.BNMap.spatialReference,
  });
  // 绘制颜色层内容
  const sectorGrp = store.BNMap.graphic(polygon, sectorsym);
  drawLayer.add(sectorGrp);
  store.BNMap.addGraphicsLayer(drawLayer);
};

const mapLoadEvent = () => {
  // draw("polygon");
  // ElMessage("需点击地图一下开始绘制");
  drawLayer = store.BNMap.creatGraphicsLayer({ id: "demo" });
  drawAreaOnMap(vcoordinate.value);
};
const mapClick = () => {
  draw("polygon");
};
/**
 * @functionName 地图区域选择功能
 * @description
 * @author 彭庆楠
 * @date 2023-08-17 17:56:50
 * @version V1.0.0
 * @return
 */
// 用来输出画图后对应的坐标点集合,参数值来自于Map.html
const myRings = ref();
function bnSketchComplete(rings) {
  // 自行添加坐标值的处理代码
  myRings.value = rings;
}
// 用来确保Map.html能够调用该页面的bnSketchComplete方法并返回参数
window["bnSketchComplete"] = (rings) => {
  bnSketchComplete(rings);
};

let tool = null;
const draw = (type: string) => {
  // "point"：点、"line"：线、"freeline"：自由线、 "polygon"：面
  // "circle"：圆、"curve"：弧线、"freehandarrow"：箭头、"multihead"：多箭头、"beziercurve"：bezier线、"bezierpolygon"：bezier面
  // drawMap();
  // tool.activate(type);
  //以上两句为原始绘画代码
  store.BASE.polygon();
};
//原来地图绘画（未启用）
const drawMap = () => {
  store.BNMap.removeGraphicsLayer("demo");
  // 向地图添加临时图层
  const clickLayer = store.BNMap.creatGraphicsLayer({ id: "demo" });
  clickLayer.removeAll();
  store.BNMap.addGraphicsLayer(clickLayer);
  tool = store.BNMap.createPlot(
    {
      gl: clickLayer, // 指定操作图层
      fillSymbol: {
        // 设置绘制面样式
        color: [227, 139, 79, 0.8],
        outline: {
          color: [255, 255, 255],
          width: 1,
        },
      },
      lineSymbol: {
        color: [226, 119, 40],
        width: 2,
      },
      pointSymbol: {
        color: [226, 119, 40],
        outline: {
          color: [255, 255, 255],
          width: 2,
        },
      },
    },
    {
      // 参数二：绑定事件
      complete: function (e: any) {
        // 传接口只需要传递e.graphic.geometry.rings
        // 为了显示处理为字符串,字符串无需传给接口
        const temp = ref("");

        e.graphic.geometry.rings[0].forEach((r: any) => {
          temp.value += r[0] + "," + r[1] + ";";
          const arr = ref({
            latitude: "",
            longitude: "",
          });
          arr.value.latitude = r[0];
          arr.value.longitude = r[1];
          vcoordinate.value.push(arr.value);
        });
        if (FilterRef.value) {
          FilterRef.value.setFieldsValue({
            coordinate: e.graphic.geometry.rings,
          });
          isdialogOptions.value[8].defaultValue =
            FilterRef.value.getParams().coordinate;
        } else {
          isdialogOptions.value[8].defaultValue = e.graphic.geometry.rings;
        }
      },
    }
  );
};
//  默认小于1年，进行维护提示
const remindtype = reactive({
  beforePeriod: 1,
  prompt: "Y",
});
// 获取维护字典
const getremind = () => {
  getResource("house_mainten_time").then((resp: any) => {
    let str = resp.data.properties.meta.params;
    str = str.replace(/'/g, '"');
    remindtype.beforePeriod = JSON.parse(str).time;
    remindtype.prompt = JSON.parse(str).unit;
  });
};
const remindRef = ref({});
/**
 * @functionName 房屋维护提醒
 * @param {any} k 用来判断是否更改提示日期
 * @description
 * @author 陈振兵
 * @date 2023-08-08 17:57:51
 * @version V1.0.0
 * @return
 */
const handleSubmit = async (k?: any) => {
  remindList.value = [];
  thresholdDialogVisible.value = false;
  // 在维保期限前
  const beforePeriod = ref();
  // 进行提示
  const prompt = ref();
  if (!k.beforePeriod) {
    const params = remindRef.value.getParams();
    const data = {
      key: "house_mainten_time",
      properties: {
        meta: {
          params: JSON.stringify(params).replace(/"/g, "'"),
        },
        type: "OBJECT",
      },
    };
    await postResource(data);
    remindtype.beforePeriod = params.time;
    remindtype.prompt = params.unit;
  }
  await getremind();
  beforePeriod.value = remindtype.beforePeriod;
  prompt.value = remindtype.prompt;
  // 循环tabledata.value，比较最近一次维保时间
  tabledata.value.forEach((item: any) => {
    if (item.state !== "2") {
      // 维保年限
      const maintainLimit = item.maintainLimit;
      // 处理最近一次维保时间
      const date = new Date(item.maintainTime);
      year.value = date.getFullYear();
      month.value = date.getMonth() + 1;
      day.value = date.getDate();
      // 处理当前日期
      const date1 = new Date();
      const year1 = date1.getFullYear();
      const month1 = date1.getMonth() + 1;
      const day1 = date1.getDate();
      // 维保年限 + 最近一次维保时间的年份
      const sumYear = maintainLimit * 1 + year.value;
      // 进行提示 - 年
      if (
        prompt.value === "Y" &&
        sumYear - year1 <= beforePeriod.value &&
        sumYear - year1 >= 0
      ) {
        remindList.value.push(item.houseId);
      } else if (prompt.value === "M") {
        // 进行提示 - 月
        if (
          12 * (sumYear - year1) +
            (month.value - month1) +
            (day1 - day.value) / 30 <=
            beforePeriod.value &&
          12 * (sumYear - year1) +
            (month.value - month1) +
            (day1 - day.value) / 30 >=
            0
        ) {
          remindList.value.push(item.houseId);
        }
      } else if (
        // 进行提示 - 日
        prompt.value === "D" &&
        365 * (sumYear - year1) +
          30 * (month.value - month1) +
          (day.value - day1) <=
          beforePeriod.value &&
        365 * (sumYear - year1) +
          30 * (month.value - month1) +
          (day.value - day1) <=
          month.value - month1 >=
          0
      ) {
        remindList.value.push(item.houseId);
      } else if (
        // 进行提示 - 周
        prompt.value === "W" &&
        365 * (sumYear - year1) +
          30 * (month.value - month1) +
          (day.value - day1) <=
          beforePeriod.value * 7 &&
        365 * (sumYear - year1) +
          30 * (month.value - month1) +
          (day.value - day1) <=
          month.value - month1 >=
          0
      ) {
        remindList.value.push(item.houseId);
      } else if (
        // 进行提示 - 季度
        prompt.value === "Q" &&
        12 * (sumYear - year1) +
          (month.value - month1) +
          (day1 - day.value) / 30 <=
          beforePeriod.value * 3 &&
        12 * (sumYear - year1) +
          (month.value - month1) +
          (day1 - day.value) / 30 >=
          0
      ) {
        remindList.value.push(item.houseId);
      }
    }
  });
};

onBeforeMount(() => {
  getHouseCategory("house_category");
  getHouseCategory("house_region");
  getHouseCategory("house_ability");
  getHouseCategory("house_nature");
  getData();
  organlist();
});
</script>
<style scoped>
.maintenance {
  ::v-deep .select-trigger {
    left: -124px;
    right: 20px;
    position: absolute;
  }
  ::v-deep .el-form-item__label {
    width: 110px !important;
  }
}
</style>
